﻿package CutLoad.cookies
{
	/**
	 * php与flash通信数据加密          flash部份
	 * @author smallerbird mail:smallerbird@gmail.com  site:www.mkigm.com QQ群:49983196
	 * 
	 */
	public class CEncryptFlashPhp
	{
		/**
		 * 编码
		 * @param data 要加密的数据
		 * @param key 密码参考，只是数字的字符串,例如：$key='123123123';
		 * @return 
		 * 
		 */		
		public static function encode(data:String,key:String):String{
			data=Base64.encode(data);
			data=ListInsert(data,key);
			data=Base64.encode(data);
			data=enCodeStr(data,key)
			return data;
		}
		/**
		 * 解码 
		 * @param data 要加密的数据
		 * @param key 密码参考，要与编码前的一些
		 * @return 
		 * 
		 */		
		public static function decode(data:String,key:String):String{
			data=deCodeStr(data,key);
			data=Base64.decode(data);
			if(data.indexOf(key)==-1){
				return "";
			}
			data=data.replace(key,'');
			data=Base64.decode(data);
			return data;
		}
		private static function ListInsert(str:String,inserStr:String,here:Number=-1):String{
			var x1:String=str;
			var charY:String=inserStr;
			var maxValue:Number=x1.length;
			var yy:Number=0;
			if(here<0){
				yy=getRndInt(0,maxValue);
			}else{
				here=Number(here);
				if(here>maxValue) here=maxValue;
				yy=here;
			}
			if (yy == 0) {
				return charY+x1;
			}
			if (yy == maxValue) {
				return x1+charY;
			}
			var zz:String=x1.substr(0,yy);
			x1=x1.substr(yy,x1.length);
			return zz+charY+x1;
		}
		public static function getRndInt(min:Number, max:Number):Number {
			return int(Math.random()*(max-min+1))+min;
		}
		private static function getOneCharFromStr(string:String,index:Number):Array{
			var arrResult:Array=new Array();
			var len:Number=string.length;
			var lenTem:Number=len-1;
			if(index>len-1) index=len-1;
			if(index<0) index=0;
			var center:String=string.substr(index,1);
			
			var left:String='';
			var leftTem:Number=index;
			if(leftTem>=0){
				left=string.substr(0,leftTem);
			}
			var right:String='';
			var rightTem:Number=index+1;
			if(rightTem<=lenTem){
				right=string.substr(rightTem,lenTem-rightTem+1);
			}
			arrResult.push(left);
			arrResult.push(center);
			arrResult.push(right);
			return arrResult;
		}
		private static function enCodeStr(code:String,key:String):String{
			var cc:Number=key.length;
			var arrKey:Array=key.split('')
			for(var i:Number=0;i<cc;i++){
				var intTem:Number=Number(arrKey[i]);
				var arr:Array=getOneCharFromStr(code,intTem);
				code=arr[0]+arr[2]+arr[1];
			}
			return code;
		}
		private static function deCodeStr(code:String,key:String):String{
			var cc:Number=key.length;
			var arrKey:Array=key.split('').reverse();
			for(var i:Number=0;i<arrKey.length;i++){
				var intTem:Number=Number(arrKey[i]);
				var arr:Array=getOneCharFromStr(code,code.length);
				var arr1:Array=getOneCharFromStr(arr[0],intTem);
				code=arr1[0]+arr[1]+arr1[1]+arr1[2];
			}
			return code;
		}
	}
}